import axios from 'axios'
import { Message } from '@arco-design/web-vue'

// 创建axios实例
const api = axios.create({
  baseURL: 'https://api.xiaohongshu-helper.com', // 替换为实际API地址
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    const { data } = response
    if (data.code === 200) {
      return data.data
    } else {
      Message.error(data.message || '请求失败')
      return Promise.reject(new Error(data.message || '请求失败'))
    }
  },
  (error) => {
    let message = '网络错误'
    
    if (error.response) {
      const { status, data } = error.response
      switch (status) {
        case 401:
          message = '未授权，请重新登录'
          // 清除token并跳转登录页
          localStorage.removeItem('token')
          chrome.storage.local.remove(['user'])
          break
        case 403:
          message = '拒绝访问'
          break
        case 404:
          message = '请求地址不存在'
          break
        case 500:
          message = '服务器内部错误'
          break
        default:
          message = data?.message || `错误${status}`
      }
    } else if (error.request) {
      message = '网络连接失败'
    } else {
      message = error.message
    }
    
    Message.error(message)
    return Promise.reject(error)
  }
)

// API接口定义
export const userApi = {
  // 用户登录
  login: (data) => api.post('/auth/login', data),
  
  // 用户注册
  register: (data) => api.post('/auth/register', data),
  
  // 获取用户信息
  getUserInfo: () => api.get('/user/info'),
  
  // 发送验证码
  sendCaptcha: (email) => api.post('/auth/captcha', { email })
}

export const contentApi = {
  // 分析内容
  analyzeContent: (data) => api.post('/content/analyze', data),
  
  // 生成标签
  generateTags: (data) => api.post('/content/tags', data),
  
  // 获取统计数据
  getStats: () => api.get('/stats/user')
}

export const feedbackApi = {
  // 提交反馈
  submitFeedback: (data) => api.post('/feedback/submit', data),
  
  // 获取反馈列表
  getFeedbackList: () => api.get('/feedback/list')
}

export default api 